 'WalmartOne Schedule Grabber v1.1.1
'Brian Haasen
'3/22/2013

Option Strict On
Option Explicit On
Option Infer Off

Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Collections.Specialized
Imports System.Globalization


Public Class MainForm

    Dim Desciption As String
    Dim StartTime As String
    Dim EndTime As String
    Dim StartDate As DateTime = DateTime.Now.ToString("MM/dd/yyyy")
    Dim EndDate As DateTime = DateTime.Now.ToString("MM/dd/yyyy")


    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        'Inputs user data into webbrowser
        Dim theElementCollection As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("input")
        For Each curElement As HtmlElement In theElementCollection
            Dim controlName As String = curElement.GetAttribute("name").ToString
            If controlName = "user" Then
                curElement.SetAttribute("Value", UsernameTextBox.Text)
            ElseIf controlName = "password" Then
                curElement.SetAttribute("Value", PasswordTextBox.Text)
            End If
        Next

        'Clicks login button on webpage
        Dim EtheElementCollection As HtmlElementCollection = Me.WebBrowser1.Document.GetElementsByTagName("input")
        For Each curElement As HtmlElement In EtheElementCollection
            If curElement.GetAttribute("value").Equals("Login") Then
                curElement.InvokeMember("click")
            End If
        Next

        'Loads schedule in new browser
        Using MyBrowser As New WebBrowser
            MyBrowser.Navigate("https://login.walmartone.com/onlineschedule/schedule/FullSchedule.aspx")
            'Waits for page to load
            While MyBrowser.ReadyState <> WebBrowserReadyState.Complete
                Application.DoEvents()
            End While
            'Determine if username or password are wrong based on url redirect
            If WebBrowser1.Url.ToString = "https://login.walmartone.com/cleartrust/WalmartOne/login.html?error=1" OrElse MyBrowser.Url.ToString = "https://login.walmartone.com/cleartrust/WalmartOne/login.html?error=1" Then
                StatusLabel.Text = "Wrong Username or Password."
            End If
            'Wait for page to load
            If WebBrowser1.IsBusy Then Return ' <=== tihs is an important test
            If (WebBrowser1.ReadyState = WebBrowserReadyState.Complete) Then ' <== so is this important critiera
                'Saves plain text from <div id="weekView" > containing work hours and catches error
                Try
                    My.Computer.FileSystem.WriteAllText("temp\tempschedule.txt", MyBrowser.Document.GetElementById("weekView").InnerText, False)
                    StatusLabel.Text = "Logged In Successfully"
                    SaveButton.Enabled = True
                    MyBrowser.Stop()
                    WebBrowser1.Stop()
                Catch 'ex As Exception
                End Try
            End If
        End Using
    End Sub

    Private Sub LoginButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoginButton.Click
        'Displays error message if user does not fill either textbox, else navigate to login page on click
        If UsernameTextBox.Text = String.Empty Then
            MessageBox.Show("Please enter a Username.", "Data Entry Required", MessageBoxButtons.OK, MessageBoxIcon.Information)
            UsernameTextBox.Focus()
        ElseIf PasswordTextBox.Text = String.Empty Then
            MessageBox.Show("Please enter a Password.", "Data Entry Required", MessageBoxButtons.OK, MessageBoxIcon.Information)
            PasswordTextBox.Focus()
        Else
            StatusLabel.Text = "Logging In..."
            WebBrowser1.ScriptErrorsSuppressed = True
            WebBrowser1.Navigate("https://login.walmartone.com/cleartrust/WalmartOne/login.html")
        End If
    End Sub

    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        'Declare variable to store current year(YYYY)
        Dim Yr As String
        Yr = Year(Now).ToString

        'Stop webbrowser
        WebBrowser1.Stop()

        'Load tempschedule.txt into array to be used for formatting
        Dim lines() As String = IO.File.ReadAllLines("temp\tempschedule.txt")

        'Creat Schedule.txt and write the header format we will be saving each shift as
        My.Computer.FileSystem.WriteAllText("temp\Schedule.txt", "Subject,Start Date,Start Time,End Date,End Time,All Day Event,Description" & ControlChars.NewLine, False)

        'Declare variable(LineCount) to keep track of which line the loop we are currently on
        Dim LineCount As Integer = 0

        'Loops through the array
        For Each line As String In lines

            'Formats current day of week as three letter abbreviation(ex.SAT)
            'and stores it in dayofweek
            Dim format As String = "ddd"
            Dim dayofweek As String = StartDate.ToString(format).ToUpper

            'Formats current day of month as two digits and stores it
            'in dayofmonth
            format = "dd"
            Dim dayofmonth As String = StartDate.ToString(format)

            'Combines dayofwek and dayofmonth to create a matching format
            Dim DateSearch As String = dayofweek + dayofmonth

            'Invoke the Match method and copy everything after match to variable s
            Dim s As Match = Regex.Match(line, _
                             DateSearch & "(.+)", _
                             RegexOptions.IgnoreCase)

            'If successful, write the group
            If (s.Success) Then
                Desciption = s.Groups(1).Value
                'Makes sure the match doesnt contain "Nothing currently scheduled"
                If Desciption.Contains("Nothing currently scheduled") = False Then
                    'Splits the work shift in format "7am - 3pm" at each space
                    'and stores the start time and end time in defined variables
                    Dim words As String() = Desciption.Split(CChar(" "))
                    StartTime = words(0)
                    EndTime = words(2)

                    'Check if shift crosses into a new day by checking if
                    'StartDate contains pm and EndTime contains am
                    Dim firstresult As String = String.Empty
                    If StartTime.Length >= 3 Then
                        firstresult = StartTime.Substring(StartTime.Length - 2)
                    End If
                    Dim secondresult As String = String.Empty
                    If EndTime.Length >= 3 Then
                        secondresult = EndTime.Substring(EndTime.Length - 2)
                    End If
                    If firstresult = "pm" AndAlso secondresult = "am" Then
                        EndDate = StartDate.AddDays(1)
                    Else
                        EndDate = StartDate
                    End If

                    'Formats StartTime into format hh:mmtt(ex.07:00pm)
                    If StartTime.Length = 3 Then
                        StartTime = StartTime.Insert(1, ":00")
                        StartTime = "0" & StartTime
                    End If
                    If StartTime.Length = 4 Then
                        StartTime = StartTime.Insert(2, ":00")
                    End If
                    If StartTime.Length = 6 Then
                        StartTime = "0" & StartTime
                    End If

                    'Formats EndTime into format hh:mmtt(ex.07:00pm)
                    If EndTime.Length = 3 Then
                        EndTime = EndTime.Insert(1, ":00")
                        EndTime = "0" & EndTime
                    End If
                    If EndTime.Length = 4 Then
                        EndTime = EndTime.Insert(2, ":00")
                    End If
                    If EndTime.Length = 6 Then
                        EndTime = "0" & EndTime
                    End If

                    'Formats StartTime and EndTime in 24hour format HH:mm(ex.22:00)
                    Dim aDateTime As DateTime
                    aDateTime = DateTime.ParseExact(StartTime, "h:mmtt", Nothing)
                    StartTime = aDateTime.ToString("HH:mm")
                    aDateTime = DateTime.ParseExact(EndTime, "h:mmtt", Nothing)
                    EndTime = aDateTime.ToString("HH:mm")
                End If

                'Saves corrected format to Schedule.txt for each match and increments StartDate by one
                My.Computer.FileSystem.WriteAllText("temp\Schedule.txt", "Work Shift, " & StartDate & "," & StartTime & "," & EndDate & "," & EndTime & "," & "False" & "," & Desciption & ControlChars.NewLine, True)
                StartDate = StartDate.AddDays(1)
            End If

            'Increment line counter
            LineCount += 1
        Next

        'Imports Schedule.txt into array skipping lines for lines containing "Nothing currently scheduled"
        Dim sTemp As String = String.Empty
        Dim arTemp() As String = IO.File.ReadAllLines("temp\Schedule.txt")
        'Loop through array
        For Each txtLine As String In arTemp
            'Check for line that contains preselected text and skip if .Contains.
            If Not txtLine.Contains("Nothing currently scheduled") Then
                'If not in line, add to string.
                If Not sTemp = "" Then sTemp &= vbNewLine & txtLine Else sTemp = txtLine
            End If
        Next

        'Save file dialog to save STemp array
        Dim saveFileDialog As New SaveFileDialog()
        Dim SuggestedName As String = "Walmart Work Schedule"
        saveFileDialog.Filter = "csv files (*.csv)|*.txt|All files (*.*)|*.*"
        saveFileDialog.FilterIndex = 1
        saveFileDialog.RestoreDirectory = True
        saveFileDialog.FileName = SuggestedName + ".csv"
        If saveFileDialog.ShowDialog() = DialogResult.OK Then
            If saveFileDialog.FileName <> "" Then
                System.IO.File.WriteAllText(saveFileDialog.FileName, sTemp)
            End If
        End If

        'Deletes temporary schedule files
        My.Computer.FileSystem.DeleteFile("temp\Schedule.txt")
        My.Computer.FileSystem.DeleteFile("temp\tempschedule.txt")

        StatusLabel.Text = "Save Successfull"
    End Sub

    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Set focus to UsernameTextBox & disable SaveButton
        UsernameTextBox.Focus()
        SaveButton.Enabled = False
    End Sub


End Class

